package com.yue.gmall.product.utils;

import org.hibernate.validator.HibernateValidator;
import org.springframework.core.MethodParameter;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author yuelinbo
 * @date 2020/4/25 23:11
 **/
public class ValidationUtils {

    private static Validator validator = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            //true 遇到第一个参数校验不同过就返回
            .failFast(false)
            .buildValidatorFactory()
            .getValidator();


    public static <T> void validate(T obj,Class c) {

        BindException bindException = new BindException(obj, "OBJECT");
        Set<ConstraintViolation<T>> validate = validator.validate(obj,c);
        for(ConstraintViolation<T> constraintViolation : validate) {
            throw new ValidationException(constraintViolation.getPropertyPath()+":"+constraintViolation.getMessage());
        }





//        for (ConstraintViolation<T> constraintViolation : validate) {
//            System.out.println(constraintViolation.getMessage());
//        }



    }
}
